package com.bree.erp.data.xls.imp.sheet;

import javax.persistence.EntityManager;

import jxl.Sheet;

import com.bree.erp.data.xls.imp.AbstractSheet;
import com.bree.erp.entity.Address;
import com.bree.erp.entity.PhoneType;
import com.bree.erp.entity.Supplier;
import com.bree.erp.service.SupplierService;
import com.bree.erp.service.stateless.SupplierServiceBean;

public class SupplierSheet extends AbstractSheet {

	public SupplierSheet(Sheet sheet) {
		super(sheet);
	}

	@Override
	public void importSheet(EntityManager em) {
		Sheet sheet = this.getSheet();
		
		SupplierService service = new SupplierServiceBean(em);

		
		for (int row = 1; row < sheet.getRows(); row++) {
			String name = sheet.getCell(0, row).getContents().trim();
			String remarks = sheet.getCell(1, row).getContents().trim();
			String landline = sheet.getCell(2, row).getContents().trim();
			String mobile = sheet.getCell(3, row).getContents().trim();
			String fax = sheet.getCell(4, row).getContents().trim();
			String email = sheet.getCell(5, row).getContents().trim();
			String streeNum = sheet.getCell(6, row).getContents().trim();
			String streeName = sheet.getCell(7, row).getContents().trim();
			String building = sheet.getCell(8, row).getContents().trim();
			String barangay = sheet.getCell(9, row).getContents().trim();
			String district = sheet.getCell(10, row).getContents().trim();
			String city = sheet.getCell(11, row).getContents().trim();
			String province = sheet.getCell(12, row).getContents().trim();
			String country = sheet.getCell(13, row).getContents().trim();
			String zip = sheet.getCell(14, row).getContents().trim();
			String contactPerson = sheet.getCell(15, row).getContents().trim();

			em.getTransaction().begin();
			
			Supplier supplier = service.create(name, remarks);

			em.getTransaction().commit();
			
			em.getTransaction().begin();
			if(notEmpty(landline)) {
				service.update(supplier.getId(), PhoneType.LANDLINE, landline);
			}
			
			if(notEmpty(mobile)) {
				service.update(supplier.getId(), PhoneType.MOBILE, mobile);
			}
			
			if(notEmpty(fax)) {
				service.update(supplier.getId(), PhoneType.FAX, fax);
			}
			
			if(notEmpty(email)) {
				service.update(supplier.getId(), PhoneType.EMAIL, email);
			}
			
			
			
			Address address = new Address();
			address.setNumber(streeNum);
			address.setStreet(streeName);
			address.setBuilding(building);
			address.setBarangay(barangay);
			address.setDistrict(district);
			address.setCity(city);
			address.setProvince(province);
			address.setCountry(country);
			address.setZip(zip);
			address.setContactPerson(contactPerson);
			
			service.update(supplier.getId(), address);
			
			em.getTransaction().commit();
		}
		
	}

	private boolean notEmpty(String value) {
		
		if(value != null && value.trim().length() > 0) {
			return true;
		}
		
		return false;
	}

}
